package com.wxy.ej.flow.modules.testEmployer.controller.beanController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rt.easyjava.common.base.Result;
import com.rt.easyjava.common.utils.others.DateTool;
import com.rt.easyjava.common.base.MyQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import com.rt.easyjava.common.base.UserDetailsDto;
import com.rt.easyjava.common.config.dozer.MyMapper;
import com.rt.easyjava.common.base.PageDto;
import com.wxy.ej.flow.modules.testEmployer.dto.TestEmployerDto;
import com.wxy.ej.flow.modules.testEmployer.bean.TestEmployer;
import com.wxy.ej.flow.modules.testEmployer.service.beanService.TestEmployerService;
import java.util.List;

/**
* 前端控制器
* 1，每个bean的Controller, 根据实际情况，查以删除不用的方法
* 2，用户信息可直接形参获取：String (_userId，_loginName，_userName，_companyId，userDetailsJson)
* @author wuxiaoyong
* @since 2022-05-16
*/
@Slf4j
@Api(tags = "TestEmployerController -  控制类")
@RequestMapping("/coding/testEmployer")
@Controller
public class TestEmployerController {
    @Autowired
    protected MyMapper mapper;
    @Autowired
    protected TestEmployerService testEmployerService;

    @PreAuthorize("hasAuthority('taskflow:testEmployer:query')")
    @ApiOperation("分页查询列表（适合单表查询）")
    @GetMapping(value = "/page")
    @ResponseBody
    public Result page(@ModelAttribute TestEmployerDto testEmployerDto, String userDetailsJson){
        UserDetailsDto userDetailsDto = UserDetailsDto.getUserDetailsDto(userDetailsJson, "testEmployer:query");
        Page<TestEmployer> page = new Page<>(testEmployerDto.getPage(), testEmployerDto.getLimit());

        // 查询条件
        TestEmployer testEmployerQuery = mapper.map(testEmployerDto, TestEmployer.class);
        // set deleteflag default 0, 查询参数时，默认只查有效数据
        testEmployerQuery.setDeleteflagDefaultZero();
        // 数据访问边界 0：全部数据， 10：机构内部数据
        testEmployerQuery.rebuildDataLimitQueryBean(userDetailsDto);

        QueryWrapper<TestEmployer> queryWrapper=new QueryWrapper<>(testEmployerQuery);
        //特殊查询条件
        queryWrapper.ge(testEmployerDto.getCreateTime_Start()!=null,"create_time",testEmployerDto.getCreateTime_Start());
        queryWrapper.le(testEmployerDto.getCreateTime_End()!=null,"create_time",testEmployerDto.getCreateTime_End());
        // queryWrapper.orderBy(testEmployerDto.getCondition(), testEmployerDto.isAsc(), testEmployerDto.getColumn());
        // 支持前端：listQuery.sort='-part_no,-id'
        for (PageDto sortDto:testEmployerDto.getSortList()){
            queryWrapper.orderBy(true, sortDto.getAsc(), sortDto.getColumn());
        }

        return testEmployerService.page(page, queryWrapper);
    }

    /**
        树结构查询方法，非树结构会造一个空方法备用着。
    */
    @PreAuthorize("hasAuthority('taskflow:testEmployer:query')")
    @ApiOperation("以ID作为父节点，查询子树")
    @GetMapping(value = "/tree")
    @ResponseBody
    public Result tree (Long id) {
        Result<TestEmployerDto> result = new Result<>();
        // when id=0 , id=0 is parantId=0 , 默认设置一个空根
        TestEmployerDto testEmployerDto = new TestEmployerDto();
        testEmployerDto.setId(0L);
        if (id!=0) {
            TestEmployer testEmployer = testEmployerService.getById(id);
            testEmployerDto = mapper.map(testEmployer, TestEmployerDto.class);
        }
        treeReduce(testEmployerDto);
        result.setObj(testEmployerDto);

        return result.success();
    }

    private void treeReduce(TestEmployerDto testEmployerDto){
    }

    @PreAuthorize("hasAuthority('taskflow:testEmployer:query')")
    @ApiOperation("自定义sql分页查询（mapper.xml, 适合多表查询）")
    @GetMapping(value = "/myPage")
    @ResponseBody
    public Result myPage(@ModelAttribute TestEmployerDto testEmployerDto, String userDetailsJson){
        UserDetailsDto userDetailsDto = UserDetailsDto.getUserDetailsDto(userDetailsJson, "testEmployer:query");
        Page<TestEmployer> page = new Page<>(testEmployerDto.getPage(), testEmployerDto.getLimit());

        // 查询条件
        TestEmployer testEmployerQuery = mapper.map(testEmployerDto, TestEmployer.class);
        // set deleteflag default 0, 查询参数时，默认只查有效数据
        testEmployerQuery.setDeleteflagDefaultZero();
        // 数据访问边界 0：全部数据， 10：机构内部数据
        testEmployerQuery.rebuildDataLimitQueryBean(userDetailsDto);

        // 多表查询时，plus自带不支持，这里封装一个工具类处理，mapper.xml中主表别名是t1, 给所有非空字段加别名； 特殊查询条件，在工具类中要忽略掉，最后自定义增加。
        QueryWrapper<TestEmployer> queryWrapper = MyQueryWrapper.buildQueryWrapper(testEmployerQuery , "create_time");
        //特殊查询条件
        queryWrapper.ge(testEmployerDto.getCreateTime_Start()!=null,"t1.create_time",testEmployerDto.getCreateTime_Start());
        queryWrapper.le(testEmployerDto.getCreateTime_End()!=null,"t1.create_time",testEmployerDto.getCreateTime_End());
        // queryWrapper.orderBy(testEmployerDto.getCondition(), testEmployerDto.isAsc(), "t1."+testEmployerDto.getColumn());
        // 支持前端：listQuery.sort='-part_no,-id'
        for (PageDto sortDto:testEmployerDto.getSortList()){
            queryWrapper.orderBy(true, sortDto.getAsc(), "t1."+sortDto.getColumn());
        }

        return testEmployerService.myPage(page, queryWrapper, testEmployerDto.getHasFooter());
    }



    @PreAuthorize("hasAuthority('taskflow:testEmployer:query')")
    @ApiOperation("查询所有")
    @GetMapping(value = "/selectBy")
    @ResponseBody
    public Result selectBy(@ModelAttribute TestEmployerDto testEmployerDto, String userDetailsJson){
        UserDetailsDto userDetailsDto = UserDetailsDto.getUserDetailsDto(userDetailsJson, "testEmployer:query");
        Result<TestEmployerDto> result = new Result<>();

        // 查询条件
        TestEmployer testEmployerQuery = mapper.map(testEmployerDto, TestEmployer.class);
        // set deleteflag default 0, 查询参数时，默认只查有效数据
        testEmployerQuery.setDeleteflagDefaultZero();
        // 数据访问边界 0：全部数据， 10：机构内部数据
        testEmployerQuery.rebuildDataLimitQueryBean(userDetailsDto);

        QueryWrapper<TestEmployer> queryWrapper=new QueryWrapper<>(testEmployerQuery);
        //特殊查询条件
        queryWrapper.ge(testEmployerDto.getCreateTime_Start()!=null,"create_time",testEmployerDto.getCreateTime_Start());
        queryWrapper.le(testEmployerDto.getCreateTime_End()!=null,"create_time",testEmployerDto.getCreateTime_End());
        queryWrapper.orderBy(testEmployerDto.getCondition(), testEmployerDto.isAsc(), testEmployerDto.getColumn());

        result = testEmployerService.selectBy(queryWrapper);

        return result;
    }

    @PreAuthorize("hasAuthority('taskflow:testEmployer:query')")
    @ApiOperation("selectById")
    @GetMapping(value = "/selectById")
    @ResponseBody
    public Result selectById(Long id){
        return testEmployerService.selectById(id);
    }

    @PreAuthorize("hasAuthority('taskflow:testEmployer:query')")
    @ApiOperation("SQL动态多选项, spring动态调用")
    @GetMapping(value = "/select4column")
    @ResponseBody
    public Result select4column(String columnName){
        return testEmployerService.select4column(columnName);
    }

    @PreAuthorize("hasAuthority('taskflow:testEmployer:create')")
    @ApiOperation("新增对象")
    @PostMapping(value = "/create")
    @ResponseBody
    public Result create(@RequestBody TestEmployerDto testEmployerDto, String userDetailsJson){
        //插入参数
        testEmployerDto.setCreatorUpdatorInfo(userDetailsJson);

        //调用服务
        return testEmployerService.create(testEmployerDto);
    }

    @PreAuthorize("hasAuthority('taskflow:testEmployer:update')")
    @ApiOperation("编辑对象")
    @PostMapping(value = "/update")
    @ResponseBody
    public Result update(@RequestBody TestEmployerDto testEmployerDto, String userDetailsJson){
        try{
            testEmployerDto.getId().longValue();
        }catch (Exception e){
            return Result.builder().fault("数据中缺少ID");
        }

        //参数
        testEmployerDto.setUpdatorInfo(userDetailsJson);

        //调用服务
        return testEmployerService.updateByDtoId(testEmployerDto);
    }

    @PreAuthorize("hasAuthority('taskflow:testEmployer:delete')")
    @ApiOperation("逻辑删除对象，由deleteflag控制：0:有效，1:已删除。")
    @PostMapping(value = "/delete")
    @ResponseBody
    public Result delete(Long id, String userDetailsJson){
        try{
            id.longValue();
        }catch (Exception e){
            return Result.builder().fault("数据中缺少ID");
        }
        //参数
        TestEmployerDto testEmployerDto = new TestEmployerDto();
        testEmployerDto.setUpdatorInfo(userDetailsJson);
        testEmployerDto.setId(id);
        testEmployerDto.setDeleteFlag(1);

        //调用服务
        return testEmployerService.updateByDtoId(testEmployerDto);
    }

    @PreAuthorize("hasAuthority('taskflow:testEmployer:deletePhysical')")
    @ApiOperation("物理删除对象，默认注释了核心调用方法，请按需启用")
    @PostMapping(value = "/deletePhysical")
    @ResponseBody
    public Result deletePhysical(Long id){
        Result result = new Result();

        //调用服务
        Boolean aBoolean =  false;//testEmployerService.removeById(id==null?0:id.longValue());
        if(aBoolean){
            result.success();
        }else {
            result.fault();
        }

        return result;
    }

}
